package cn.tedu._05article.controller;

import cn.tedu._05article.base.response.JsonResult;
import cn.tedu._05article.base.response.StatusCode;
import cn.tedu._05article.mapper.UserMapper;
import cn.tedu._05article.pojo.dto.UserArticleParam;
import cn.tedu._05article.pojo.dto.UserLoginParam;
import cn.tedu._05article.pojo.entity.Article;
import cn.tedu._05article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Tag(name = "用户管理")
@Slf4j
@RestController
@RequestMapping("v1/user/")
public class UserController {
    @Autowired
    private UserMapper  userMapper;

    //  用户登录功能
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 10)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession  session) {
        log.debug("UserLoginParam:"+userLoginParam);

        UserVO userVO=userMapper.selectByUsernameAndPassword(userLoginParam);
        if (userVO!=null){
            session.setAttribute("user",userVO);
            return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);
        }
        return new JsonResult((StatusCode.USERNAME_PASSWORD_ERROR));
    }
     //发表文章功能
    @Operation(summary = "发表文章")
    @ApiOperationSupport(order = 20)
    @PostMapping("article")
    public JsonResult article(@Validated @RequestBody UserArticleParam userArticleParam, HttpSession session){
        UserVO  userVO= (UserVO) session.getAttribute("user");
        if (userVO!=null){
            Article  article=new Article();
            BeanUtils.copyProperties(userArticleParam,article);
            article.setUserId(userVO.getId());
            userMapper.insertArticle(article);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.NOT_LOGIN);

    }

    
}
